/*
 * Copyright ©2021 su binglun(9085309@qq.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *---------------------------------------------------------------------
 *-                                                                   -
 *-           Website : http://phoenix.sunny360.cn/                   -
 *-                                                                   -
 *---------------------------------------------------------------------
 */
package cn.sunny360.core.service.impl;

import cn.sunny360.core.service.SystemService;
import cn.sunny360.core.utils.Container;
import cn.sunny360.core.wrapper.DBWrapper;
import com.sohu.idcenter.IdWorker;
import io.vertx.core.Promise;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Tuple;

/**
 * implementation of {@link SystemService}.
 *
 * @author sublun
 */
public class SystemServiceImpl implements SystemService {

	private static final Logger logger = LoggerFactory.getLogger(SystemServiceImpl.class);

	private IdWorker idWorker;
	private DBWrapper dbWrapper;

	public SystemServiceImpl() {
		idWorker = Container.getComponent(IdWorker.class);
		dbWrapper = Container.getComponent(DBWrapper.class);
	}


	@Override
	public SystemService getWsUrl(Promise<String> resultHandler) {

		getConfig("websocket_url", resultHandler);

		return this;
	}

	@Override
	public SystemService getConfig(String key, Promise<String> resultHandler) {
		dbWrapper.findOne("select value from ph_system where name=?", Tuple.of(key))
				.future()
				.onFailure(resultHandler::fail)
				.onSuccess(o->{
					if(!o.isPresent()) {
						resultHandler.fail("未查询到["+key+"]对应的值！");
					} else {
						JsonObject jsonObject = o.get();
						resultHandler.complete(jsonObject.getString("value"));
					}
				});
		return this;
	}

	@Override
	public SystemService getConfigList(String category, Promise<JsonArray> resultHandler) {
		dbWrapper.findList("select name,value from ph_system where category=?", Tuple.of(category))
				.future()
				.onFailure(resultHandler::fail)
				.onSuccess(list->{
					resultHandler.complete(new JsonArray(list));
				});
		return this;
	}
}